<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"he7009.gitee.io","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="关于错误处理的几点理解  错误只应该被处理一次，写日志、降级、返回错误等都算作对错误的处理。写了日志、做了降级就不应该继续返回错误；如果返回错误，则不做其他处理。 错误应该包含错误信息和堆栈信息，以便于后续的错误查找和调试。 项目中应该尽量简洁明了的进行错误的判断处理。  早期的错误处理 package errors  &#x2F;&#x2F;创建包含错误信息的错误 func New(text string) err">
<meta property="og:type" content="article">
<meta property="og:title" content="GO Error 处理">
<meta property="og:url" content="https://he7009.gitee.io/2020/12/10/go/go-error-chu-li/index.html">
<meta property="og:site_name" content="he7009">
<meta property="og:description" content="关于错误处理的几点理解  错误只应该被处理一次，写日志、降级、返回错误等都算作对错误的处理。写了日志、做了降级就不应该继续返回错误；如果返回错误，则不做其他处理。 错误应该包含错误信息和堆栈信息，以便于后续的错误查找和调试。 项目中应该尽量简洁明了的进行错误的判断处理。  早期的错误处理 package errors  &#x2F;&#x2F;创建包含错误信息的错误 func New(text string) err">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-12-10T07:13:10.000Z">
<meta property="article:modified_time" content="2021-02-26T16:11:03.006Z">
<meta property="article:author" content="he7009">
<meta property="article:tag" content="Error">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://he7009.gitee.io/2020/12/10/go/go-error-chu-li/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>GO Error 处理 | he7009</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="he7009" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">he7009</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">天行健，君子以自强不息</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tag fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://he7009.gitee.io/2020/12/10/go/go-error-chu-li/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="he7009">
      <meta itemprop="description" content="Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="he7009">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          GO Error 处理
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-12-10 15:13:10" itemprop="dateCreated datePublished" datetime="2020-12-10T15:13:10+08:00">2020-12-10</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-02-27 00:11:03" itemprop="dateModified" datetime="2021-02-27T00:11:03+08:00">2021-02-27</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Go/" itemprop="url" rel="index"><span itemprop="name">Go</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="关于错误处理的几点理解"><a href="#关于错误处理的几点理解" class="headerlink" title="关于错误处理的几点理解"></a>关于错误处理的几点理解</h2><hr>
<ol>
<li>错误只应该被处理一次，写日志、降级、返回错误等都算作对错误的处理。写了日志、做了降级就不应该继续返回错误；如果返回错误，则不做其他处理。</li>
<li>错误应该包含错误信息和堆栈信息，以便于后续的错误查找和调试。</li>
<li>项目中应该尽量简洁明了的进行错误的判断处理。</li>
</ol>
<h2 id="早期的错误处理"><a href="#早期的错误处理" class="headerlink" title="早期的错误处理"></a>早期的错误处理</h2><hr>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> errors

<span class="token comment">//创建包含错误信息的错误</span>
<span class="token keyword">func</span> <span class="token function">New</span><span class="token punctuation">(</span>text <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token operator">&amp;</span>errorString<span class="token punctuation">&#123;</span>text<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">type</span> errorString <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	s <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现 Error 接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>e <span class="token operator">*</span>errorString<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> e<span class="token punctuation">.</span>s
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>只是简单的包含错误的信息，存在两个问题：</p>
<ul>
<li>上层无法添加错误信息</li>
<li>错误信息不包含堆栈信息；不利于调试和错误查找</li>
</ul>
<h2 id="GO-1-13-错误处理"><a href="#GO-1-13-错误处理" class="headerlink" title="GO 1.13 错误处理"></a>GO 1.13 错误处理</h2><hr>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">//errors package</span>

<span class="token comment">//判断是否实现 interface &#123; Unwrap() error &#125; 接口，实现则调用返回根错误</span>
<span class="token keyword">func</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	u<span class="token punctuation">,</span> ok <span class="token operator">:=</span> err<span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token keyword">interface</span> <span class="token punctuation">&#123;</span>
		<span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span>
	<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> <span class="token operator">!</span>ok <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> <span class="token boolean">nil</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> u<span class="token punctuation">.</span><span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">//判断 err 错误是否 等于 target 错误，或者包含 target 错误</span>
<span class="token comment">//如果 err 和 target 是同一个，那么返回true</span>
<span class="token comment">//如果 err 是一个打包(wrap) 错误;并且 err 包含 target 错误 返回true</span>
<span class="token comment">//不等于也不包含则返回false</span>
<span class="token keyword">func</span> <span class="token function">Is</span><span class="token punctuation">(</span>err<span class="token punctuation">,</span> target <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//获取错误中包含的 具体错误，方法内部进行断言</span>
<span class="token keyword">func</span> <span class="token function">As</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> target <span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">//fmt package</span>

<span class="token comment">//打包根错误、添加错误信息；实现 interface &#123; Unwrap() error &#125; 接口来返回根错误</span>
<span class="token keyword">func</span> <span class="token function">Errorf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> a <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//wrapErro struct 包装 error</span>
<span class="token keyword">type</span> wrapError <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	msg <span class="token builtin">string</span>
	err <span class="token builtin">error</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现error接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>e <span class="token operator">*</span>wrapError<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> e<span class="token punctuation">.</span>msg
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现Unwrap接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>e <span class="token operator">*</span>wrapError<span class="token punctuation">)</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> e<span class="token punctuation">.</span>err
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>GO 1.13 可以通过fmt.Errorf 对错误信息进行wrap,进而添加错误信息;与此同时 errors package 中提供了对错误的Unwrap、 Is、As 方法,用以获取根错误信息和对错误的比较、判断等</p>
<p>增加了错误信息的wrap但是还是缺少堆栈信息的保存</p>
<h2 id="pkg-errors"><a href="#pkg-errors" class="headerlink" title="pkg/errors"></a>pkg/errors</h2><hr>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">
<span class="token comment">//github.com/pkg/errors</span>

<span class="token comment">//包含堆栈信息的error</span>
<span class="token keyword">type</span> fundamental <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	msg <span class="token builtin">string</span>
	<span class="token operator">*</span>stack
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现 error 接口</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>f <span class="token operator">*</span>fundamental<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> f<span class="token punctuation">.</span>msg <span class="token punctuation">&#125;</span>
<span class="token comment">//重写format</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>f <span class="token operator">*</span>fundamental<span class="token punctuation">)</span> <span class="token function">Format</span><span class="token punctuation">(</span>s fmt<span class="token punctuation">.</span>State<span class="token punctuation">,</span> verb <span class="token builtin">rune</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">switch</span> verb <span class="token punctuation">&#123;</span>
	<span class="token keyword">case</span> <span class="token string">'v'</span><span class="token punctuation">:</span>
		<span class="token keyword">if</span> s<span class="token punctuation">.</span><span class="token function">Flag</span><span class="token punctuation">(</span><span class="token string">'+'</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			io<span class="token punctuation">.</span><span class="token function">WriteString</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> f<span class="token punctuation">.</span>msg<span class="token punctuation">)</span>
			f<span class="token punctuation">.</span>stack<span class="token punctuation">.</span><span class="token function">Format</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> verb<span class="token punctuation">)</span>
			<span class="token keyword">return</span>
		<span class="token punctuation">&#125;</span>
		<span class="token keyword">fallthrough</span>
	<span class="token keyword">case</span> <span class="token string">'s'</span><span class="token punctuation">:</span>
		io<span class="token punctuation">.</span><span class="token function">WriteString</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> f<span class="token punctuation">.</span>msg<span class="token punctuation">)</span>
	<span class="token keyword">case</span> <span class="token string">'q'</span><span class="token punctuation">:</span>
		fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> <span class="token string">"%q"</span><span class="token punctuation">,</span> f<span class="token punctuation">.</span>msg<span class="token punctuation">)</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>



<span class="token comment">// withStack struct 打包error,包含堆栈信息</span>
<span class="token keyword">type</span> withStack <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	<span class="token builtin">error</span>
	<span class="token operator">*</span>stack
<span class="token punctuation">&#125;</span>
<span class="token comment">//实现Cause接口，返回根错误</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withStack<span class="token punctuation">)</span> <span class="token function">Cause</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span><span class="token builtin">error</span> <span class="token punctuation">&#125;</span>
<span class="token comment">// 实现Unwrap接口，返回根错误（用于兼容GO 1.13）</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withStack<span class="token punctuation">)</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span><span class="token builtin">error</span> <span class="token punctuation">&#125;</span>



<span class="token comment">// withMessage 打包 error,添加错误信息</span>
<span class="token keyword">type</span> withMessage <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	cause <span class="token builtin">error</span>
	msg   <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withMessage<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span>msg <span class="token operator">+</span> <span class="token string">": "</span> <span class="token operator">+</span> w<span class="token punctuation">.</span>cause<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token comment">//实现Cause接口，返回根错误</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withMessage<span class="token punctuation">)</span> <span class="token function">Cause</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span>  <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span>cause <span class="token punctuation">&#125;</span>
<span class="token comment">// 实现Unwrap接口，返回根错误（用于兼容GO 1.13）</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>w <span class="token operator">*</span>withMessage<span class="token punctuation">)</span> <span class="token function">Unwrap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> w<span class="token punctuation">.</span>cause <span class="token punctuation">&#125;</span>



<span class="token comment">//基于 fundamental 创建包含 错误信息 和 堆栈信息 的错误</span>
<span class="token keyword">func</span> <span class="token function">New</span><span class="token punctuation">(</span>message <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">Errorf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//打包（wrap）错误;添加 堆栈信息；</span>
<span class="token comment">//实现了interface &#123; Cause() error &#125; 接口</span>
<span class="token comment">//实现了interface &#123; Unwrap() error &#125; 接口兼容 GO 1.13</span>
<span class="token keyword">func</span> <span class="token function">WithStack</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//打包（wrap）错误;添加 错误信息；</span>
<span class="token comment">//实现了interface &#123; Cause() error &#125; 接口</span>
<span class="token comment">//实现了interface &#123; Unwrap() error &#125; 接口兼容 GO 1.13</span>
<span class="token keyword">func</span> <span class="token function">WithMessage</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> message <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">WithMessagef</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//打包（wrap）错误;添加 错误信息 和 堆栈信息</span>
<span class="token comment">//实现了interface &#123; Cause() error &#125; 接口</span>
<span class="token comment">//实现了interface &#123; Unwrap() error &#125; 接口兼容 GO 1.13</span>
<span class="token keyword">func</span> <span class="token function">Wrap</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> message <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">Wrapf</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">,</span> format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">//判断是否实现 interface &#123; Cause() error &#125; 接口，实现则调用返回根错误；等同于 GO 1.13 的 Unwrap()</span>
<span class="token keyword">func</span> <span class="token function">Cause</span><span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token builtin">error</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h2 id="使用建议"><a href="#使用建议" class="headerlink" title="使用建议"></a>使用建议</h2><hr>
<ol>
<li>综合使用 GO 1.13 和 pgk/errors；pkg/errors 打包处理的错误 GO 1.13 提供的 Unwrap、Is、As 同样可以使用</li>
<li>自己应用层的代码，出现错误；可以使用 pkg/errors 的包，创建一个包含错误信息 和 堆栈信息的错误进行返回</li>
<li>对于别人返回的错误，如果是底层的未包含堆栈信息的错误可以使用 wrap 打包错误，添加错误信息 和 堆栈信息</li>
<li>对于别人返回的错误，如果是已经打包，包含 堆栈信息 的错误则直接返回。</li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Error/" rel="tag"># Error</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/12/08/go/go-time/" rel="prev" title="GO - Time">
      <i class="fa fa-chevron-left"></i> GO - Time
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/03/04/linux/linux-ssh-mian-mi-deng-lu-pei-zhi/" rel="next" title="Linux ssh免密登录配置">
      Linux ssh免密登录配置 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86%E7%9A%84%E5%87%A0%E7%82%B9%E7%90%86%E8%A7%A3"><span class="nav-number">1.</span> <span class="nav-text">关于错误处理的几点理解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%97%A9%E6%9C%9F%E7%9A%84%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86"><span class="nav-number">2.</span> <span class="nav-text">早期的错误处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GO-1-13-%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86"><span class="nav-number">3.</span> <span class="nav-text">GO 1.13 错误处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pkg-errors"><span class="nav-number">4.</span> <span class="nav-text">pkg&#x2F;errors</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%BB%BA%E8%AE%AE"><span class="nav-number">5.</span> <span class="nav-text">使用建议</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">he7009</p>
  <div class="site-description" itemprop="description">Go、PHP、Mysql、Redis、Linux、Shell、Nginx—知识分享</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">9</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">12</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">he7009</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
